package common

import (
	"fmt"
	"log"
	"ssr/models"

	"gorm.io/driver/mysql"
	"gorm.io/gorm"
)

var DB *gorm.DB

func init() {

	config := LoadingConfig()
	if config == nil {
		panic("config is nil")
	}
	host := config.Database.Host
	port := config.Database.Port
	username := config.Database.UsrName
	password := config.Database.Password

	dsn := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=utf8mb4&parseTime=True&loc=Local", username, password, host, port, config.Database.DBName)
	var err error
	DB, err = gorm.Open(mysql.Open(dsn), &gorm.Config{})
	if err != nil {
		log.Fatal("数据库连接失败:", err)
	}

	log.Println("database connect success")
	// 自动迁移表结构
	// 快三游戏模块
	// DB.AutoMigrate(&models.GameUser{}, &models.GameResult{}, &models.Bet{}, &models.OddRules{}, &models.JackPotPoll{})
	// 水票模块
	// DB.AutoMigrate(&models.WaterOrder{}, &models.WaterDict{})

	// 短链模块
	DB.AutoMigrate(&models.Link{})
}

func GetDB() *gorm.DB {
	return DB
}
